<template>
  <a-card>
    <div class="card-header">
      <a-space>
        <span class="card-header-title">数据源管理</span>
        <a-tag color="blue">{{$route.query.name}}</a-tag>
        <a-tag>{{data?.length}}</a-tag>
      </a-space>
      <a-button type="primary" @click="showModal"><plus-outlined/>新建数据</a-button>
    </div>
    <a-table :columns="columns"
             :data-source="data"
             :row-selection="{}"
             :pagination="tablePageConfig">
      <template #bodyCell="{column,record}">
        <template v-if="column.key === 'color'">
          <a-tag :color="record.color">{{record.name}}</a-tag>
        </template>
        <template v-if="column.key==='action'">
          <div class="table-action">
            <span @click="showModal(record)">编辑</span>
            <a-popconfirm title="删除确认，此操作不可逆，请谨慎操作！"
                          placement="left"
                          @confirm="onRemove(record.id)">
              <span>删除</span>
            </a-popconfirm>
          </div>
        </template>
      </template>
    </a-table>
    <data-modal @change="onChange" v-model:data="dataItem" v-model:visible="visible"/>
  </a-card>
</template>
<script setup lang="ts">
import DataModal from "./components/DataModal.vue";
import {TableColumnsType} from "ant-design-vue";
import {useRoute} from "vue-router";
import {deleteDictionaryData, getDictionaryData} from "@/api/modules/dictionary";
import {onMounted, ref} from "vue";
import useMessage from "@/plugin/useMessage";
import {tablePageConfig} from "@/config";
import {PlusOutlined} from "@ant-design/icons-vue";

const route =  useRoute()
let data = ref<DictionaryData[]>()
let dataItem = ref<DictionaryData>()
let visible = ref<boolean>(false)

const columns:TableColumnsType = [
  {key:'name',title:'名称',dataIndex:'name'},
  {key:'color',title:'样式',dataIndex:'color'},
  {key:'sort',title:'排序',dataIndex:'sort',width:120},
  {key:'action',title:'管理',width:160}
]

const getData = async ()=>{
  let res:HttpResponse  = await getDictionaryData(route.query.id)
  if(res.code === 200){
    data.value = res.data
  }else {
    useMessage(res.code,res.message)
  }
}
const onRemove = async (id:number)=>{
  let res:HttpResponse = await deleteDictionaryData(id)
  if(res.code === 200){
    data.value = data.value.filter(item => item.id !== id)
  }
  useMessage(res.code,res.message)
}

const showModal = (item?:DictionaryData)=>{
  visible.value = true
  dataItem.value = item ? item : {}
}
const onChange = (res:{model:ActionType,data:DictionaryData})=>{
  if(res.model === 'create'){
    data.value.push(item)
  }
  if(res.model === 'update'){
    //更改原来数组的值
    data.value.forEach((item,index)=>{
      if(item.id === res.data.id){
        data.value.splice(index,1,res.data)
      }
    })
  }
}
onMounted( ()=>{
  getData()
})
</script>

<style scoped>

</style>